package com.university.evaluation.utils;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtils {

    // 判断字符串是否为空
    public static boolean isEmpty(String str) {
        return str == null || str.length() == 0;
    }

    // 判断字符串是否不为空
    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }

    // 判断字符串是否为空白
    public static boolean isBlank(String str) {
        if (str == null || str.length() == 0) {
            return true;
        }
        for (int i = 0; i < str.length(); i++) {
            if (!Character.isWhitespace(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    // 判断字符串是否不为空白
    public static boolean isNotBlank(String str) {
        return !isBlank(str);
    }

    // 去除字符串首尾的空白字符
    public static String trim(String str) {
        return str == null ? null : str.trim();
    }

    // 截取字符串，超出长度的部分用指定字符替换
    public static String truncate(String str, int length, String suffix) {
        if (str == null) {
            return null;
        }
        if (length < 0) {
            throw new IllegalArgumentException("截取长度不能为负数");
        }
        if (str.length() <= length) {
            return str;
        }
        if (suffix == null) {
            suffix = "";
        }
        return str.substring(0, length - suffix.length()) + suffix;
    }

    // 首字母大写
    public static String capitalize(String str) {
        if (str == null || str.length() == 0) {
            return str;
        }
        return Character.toUpperCase(str.charAt(0)) + str.substring(1);
    }

    // 首字母小写
    public static String uncapitalize(String str) {
        if (str == null || str.length() == 0) {
            return str;
        }
        return Character.toLowerCase(str.charAt(0)) + str.substring(1);
    }

    // 将字符串转换为驼峰命名
    public static String toCamelCase(String str) {
        if (str == null || str.length() == 0) {
            return str;
        }
        StringBuilder sb = new StringBuilder();
        boolean nextUpperCase = false;
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (c == '_' || c == '-' || c == ' ' || c == '.') {
                nextUpperCase = true;
            } else {
                if (nextUpperCase) {
                    sb.append(Character.toUpperCase(c));
                    nextUpperCase = false;
                } else {
                    sb.append(Character.toLowerCase(c));
                }
            }
        }
        return sb.toString();
    }

    // 将字符串转换为下划线命名
    public static String toUnderScoreCase(String str) {
        if (str == null || str.length() == 0) {
            return str;
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (i > 0 && Character.isUpperCase(c)) {
                sb.append('_');
                sb.append(Character.toLowerCase(c));
            } else {
                sb.append(Character.toLowerCase(c));
            }
        }
        return sb.toString();
    }

    // 判断字符串是否以指定前缀开始
    public static boolean startsWith(String str, String prefix) {
        return str != null && prefix != null && str.startsWith(prefix);
    }

    // 判断字符串是否以指定后缀结束
    public static boolean endsWith(String str, String suffix) {
        return str != null && suffix != null && str.endsWith(suffix);
    }

    // 替换字符串中的指定字符
    public static String replace(String str, char oldChar, char newChar) {
        return str == null ? null : str.replace(oldChar, newChar);
    }

    // 替换字符串中的指定子串
    public static String replace(String str, String target, String replacement) {
        return str == null ? null : str.replace(target, replacement);
    }

    // 使用正则表达式替换字符串
    public static String replaceAll(String str, String regex, String replacement) {
        if (str == null || regex == null) {
            return str;
        }
        return str.replaceAll(regex, replacement);
    }

    // 判断字符串是否包含指定子串
    public static boolean contains(String str, String searchStr) {
        return str != null && searchStr != null && str.contains(searchStr);
    }

    // 判断字符串是否包含任何一个指定的子串
    public static boolean containsAny(String str, String... searchStrs) {
        if (str == null || searchStrs == null || searchStrs.length == 0) {
            return false;
        }
        for (String searchStr : searchStrs) {
            if (contains(str, searchStr)) {
                return true;
            }
        }
        return false;
    }

    // 分割字符串
    public static String[] split(String str, String separator) {
        if (str == null) {
            return null;
        }
        if (separator == null) {
            return new String[]{str};
        }
        return str.split(separator);
    }

    // 连接字符串数组
    public static String join(Object[] array, String separator) {
        if (array == null) {
            return null;
        }
        if (separator == null) {
            separator = "";
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < array.length; i++) {
            if (i > 0) {
                sb.append(separator);
            }
            sb.append(array[i]);
        }
        return sb.toString();
    }

    // 连接集合中的元素
    public static String join(Collection<?> collection, String separator) {
        if (collection == null) {
            return null;
        }
        if (separator == null) {
            separator = "";
        }
        StringBuilder sb = new StringBuilder();
        boolean first = true;
        for (Object obj : collection) {
            if (!first) {
                sb.append(separator);
            }
            first = false;
            sb.append(obj);
        }
        return sb.toString();
    }

    // 生成指定长度的随机字符串
    public static String random(int length) {
        if (length <= 0) {
            return "";
        }
        String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(chars.length());
            sb.append(chars.charAt(index));
        }
        return sb.toString();
    }

    // 生成指定长度的随机数字字符串
    public static String randomNumber(int length) {
        if (length <= 0) {
            return "";
        }
        String chars = "0123456789";
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(chars.length());
            sb.append(chars.charAt(index));
        }
        return sb.toString();
    }

    // 计算字符串的MD5值
    public static String md5(String str) {
        if (str == null) {
            return null;
        }
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            byte[] array = md.digest(str.getBytes("UTF-8"));
            StringBuilder sb = new StringBuilder();
            for (byte b : array) {
                sb.append(Integer.toHexString((b & 0xFF) | 0x100).substring(1, 3));
            }
            return sb.toString();
        } catch (Exception e) {
            throw new RuntimeException("MD5计算失败", e);
        }
    }

    // 验证邮箱格式
    public static boolean isValidEmail(String email) {
        if (email == null) {
            return false;
        }
        String regex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }

    // 验证手机号码格式
    public static boolean isValidPhone(String phone) {
        if (phone == null) {
            return false;
        }
        // 中国大陆手机号码正则表达式
        String regex = "^1[3-9]\\d{9}$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(phone);
        return matcher.matches();
    }

    // 验证身份证号码格式
    public static boolean isValidIdCard(String idCard) {
        if (idCard == null) {
            return false;
        }
        // 简单验证身份证号码格式，完整验证需要更复杂的算法
        String regex = "(^\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|X|x)$)";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(idCard);
        return matcher.matches();
    }

    // 转义HTML特殊字符
    public static String escapeHtml(String str) {
        if (str == null) {
            return null;
        }
        str = str.replace("&", "&amp;");
        str = str.replace("<", "&lt;");
        str = str.replace(">", "&gt;");
        str = str.replace("'", "&#39;");
        str = str.replace("\"", "&#34;");
        return str;
    }

    // 反转义HTML特殊字符
    public static String unescapeHtml(String str) {
        if (str == null) {
            return null;
        }
        str = str.replace("&amp;", "&");
        str = str.replace("&lt;", "<");
        str = str.replace("&gt;", ">");
        str = str.replace("&#39;", "'");
        str = str.replace("&#34;", "\"");
        return str;
    }

    // 计算字符串的相似度
    public static double similarity(String str1, String str2) {
        if (str1 == null || str2 == null) {
            return 0.0;
        }
        int len1 = str1.length();
        int len2 = str2.length();
        int maxLen = Math.max(len1, len2);
        if (maxLen == 0) {
            return 1.0;
        }
        // 使用编辑距离计算相似度
        int[][] dp = new int[len1 + 1][len2 + 1];
        for (int i = 0; i <= len1; i++) {
            dp[i][0] = i;
        }
        for (int j = 0; j <= len2; j++) {
            dp[0][j] = j;
        }
        for (int i = 1; i <= len1; i++) {
            for (int j = 1; j <= len2; j++) {
                int cost = str1.charAt(i - 1) == str2.charAt(j - 1) ? 0 : 1;
                dp[i][j] = Math.min(Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1), dp[i - 1][j - 1] + cost);
            }
        }
        return 1.0 - (double) dp[len1][len2] / maxLen;
    }
}
